﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ArienToolkits.Network
{
    /// <summary>
    /// Http消息传递类
    /// </summary>
    public class HttpTransfer
    {
        /// <summary>
        /// 发送POST请求
        /// </summary>
        /// <param name="url">请求路径</param>
        /// <param name="postData">Post消息</param>
        /// <param name="encoding">请求、响应字符编码</param>
        /// <returns></returns>
        public static async Task<string> SendPostRequest(string url, string postData, Encoding encoding, int timeout = 5000)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("请求地址不能为空");
            }

            string result = string.Empty;
            //获取Post数据字节数组
            byte[] content = encoding.GetBytes(postData);

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                //创建并设置请求对象
                request = HttpWebRequest.Create(url) as HttpWebRequest;
                request.Timeout = timeout;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = content.Length;

                if (content.Length > 0)
                {
                    //写入请求数据
                    using (Stream reqStream = await request.GetRequestStreamAsync())
                    {
                        await reqStream.WriteAsync(content, 0, content.Length);
                        await reqStream.FlushAsync();
                        reqStream.Close();
                    }
                }

                //获取响应对象
                response = await request.GetResponseAsync() as HttpWebResponse;

                //获取并读取响应结果
                using (Stream resStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(resStream, encoding))
                    {
                        result = await reader.ReadToEndAsync();
                        reader.Close();
                    }
                    resStream.Close();
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                response.Close();
            }

            return result;
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <param name="url">请求路径</param>
        /// <param name="data">Get请求消息参数</param>
        /// <param name="encoding">请求、响应字符编码</param>
        /// <returns></returns>
        public static async Task<string> SendGetRequest(string url, Dictionary<string, string> data, Encoding encoding, int timeout = 5000)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("请求地址不能为空");
            }

            string result = string.Empty;
            //获取Post数据字节数组
            if (data != null && data.Count > 0)
            {
                url += "?";
                foreach (var key in data.Keys)
                {
                    url += string.Format("{0}={1}&", key, data[key]);
                }
                //去除尾部&符号
                url = url.Substring(0, url.Length - 1);
            }

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                //创建并设置请求对象
                request = HttpWebRequest.Create(url) as HttpWebRequest;
                request.Timeout = timeout;
                request.Method = "GET";

                //获取响应对象
                response = await request.GetResponseAsync() as HttpWebResponse;

                //获取并读取响应结果
                using (Stream resStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(resStream, encoding))
                    {
                        result = await reader.ReadToEndAsync();
                        reader.Close();
                    }
                    resStream.Close();
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                response.Close();
            }

            return result;
        }
    }
}
